﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Threading;
using System.Globalization;
using BusinessObject;
using YamahaTuanTruc.BusinessService;

namespace YamahaTuanTruc
{
    public partial class FrmPart : Form
    {
        BindingList<data> tempData;

        /// <summary>
        /// Constructor's class
        /// </summary>
        public FrmPart()
        {
            InitializeComponent();
            kryptonDataGridView2.AutoSize = true;
            kryptonDataGridView2.Dock = DockStyle.Fill;

            //Disable button if there are no items shown
            this.qcbTaoMoi.Enabled = (kryptonDataGridView2.RowCount < 0);
            this.qcbCapNhat.Enabled = (kryptonDataGridView2.RowCount < 0);
            this.qcbXoa.Enabled = (kryptonDataGridView2.RowCount < 0);

            //Generate columns
            kryptonDataGridView2.AutoGenerateColumns = false;
            DataGridViewTextBoxColumn tenHangColumn = new DataGridViewTextBoxColumn();
            tenHangColumn.DataPropertyName = "StrTenHang";
            tenHangColumn.HeaderText = "Tên hàng";

            DataGridViewTextBoxColumn maHangColumn = new DataGridViewTextBoxColumn();
            maHangColumn.DataPropertyName = "StrMaHang";
            maHangColumn.HeaderText = "Mã hàng";

            DataGridViewTextBoxColumn donGiaColumn = new DataGridViewTextBoxColumn();
            donGiaColumn.DataPropertyName = "StrDonGia";
            donGiaColumn.HeaderText = "Đơn giá (VND)";

            DataGridViewTextBoxColumn loaiXeColumn = new DataGridViewTextBoxColumn();
            loaiXeColumn.DataPropertyName = "StrLoaiXe";
            loaiXeColumn.HeaderText = "Loại xe";

            kryptonDataGridView2.Columns.Add(tenHangColumn);
            kryptonDataGridView2.Columns.Add(maHangColumn);
            kryptonDataGridView2.Columns.Add(donGiaColumn);
            kryptonDataGridView2.Columns.Add(loaiXeColumn);

            //Initialize data
            tempData = new BindingList<data>();
            tempData.Add(new data("a1", "Nhớt", "10000", "Cuxi"));
            tempData.Add(new data("a2", "Nhông", "65000", null));
            tempData.Add(new data("a3", "Sên", "100000", "Serius"));
            tempData.Add(new data("a4", "Thắng trước", "50000", null));
            tempData.Add(new data("a5", "Thắng sau", "75000", "Jupiter"));
            tempData.Add(new data("a6", "Bô", "50000", null));
            tempData.Add(new data("a7", "Căm trước", "50000", "Nouvo"));
            tempData.Add(new data("a8", "Căm sau", "45000", "Cuxi"));
            tempData.Add(new data("a9", "Bộ nồi", "120000", null));

            //Update data to datagridview
            kryptonDataGridView2.DataSource = tempData;
        }

        /// <summary>
        /// Raise this event when clicking on taomoi button
        /// </summary>
        private void qcbTaoMoi_ItemActivated(object sender, Qios.DevSuite.Components.QCompositeEventArgs e)
        {
            try
            {
                eraseAllDataTextbox();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                throw;
            }

        }
        private void reload()
        {
            using (var service = new BusinessServiceClient())
            {
                PhuTung[] lst = service.getListPart();

                if (lst != null)
                {
                    for (int i = 0; i < lst.Length; i++)
                    {
                        kryptonDataGridView2.Rows.Add();
                        kryptonDataGridView2.Rows[i].Cells[0].Value = lst[i].Ten;
                        kryptonDataGridView2.Rows[i].Cells[1].Value = lst[i].ID;
                        kryptonDataGridView2.Rows[i].Cells[2].Value = lst[i].DonGia;
                        kryptonDataGridView2.Rows[i].Cells[3].Value = lst[i].Model;

                    }
                }
            }
        }
        /// <summary>
        /// Erase data on all textboxes
        /// </summary>
        public void eraseAllDataTextbox()
        {
            this.qcibMaHang.InputBox.Text = "";
            this.qcibTenHang.InputBox.Text = "";
        }

        private void bindData(int selectedRowIndex)
        {
            //Binding data from datagridview to textboxes
            if (kryptonDataGridView2[0, selectedRowIndex].Value != null)
            {
                this.qcibMaHang.InputBox.CueText = "";
                this.qcibMaHang.InputBox.Text = kryptonDataGridView2[0, selectedRowIndex].Value.ToString();
            }
            else
            {
                this.qcibMaHang.InputBox.CueText = "";
                this.qcibMaHang.InputBox.Text = "";
            }

            if (kryptonDataGridView2[1, selectedRowIndex].Value != null)
            {
                this.qcibTenHang.InputBox.CueText = "";
                this.qcibTenHang.InputBox.Text = kryptonDataGridView2[1, selectedRowIndex].Value.ToString();
            }
            else
            {
                this.qcibTenHang.InputBox.CueText = "";
                this.qcibTenHang.InputBox.Text = "";
            }

            if (kryptonDataGridView2[2, selectedRowIndex].Value != null)
            {
                try
                {
                    this.qcibDonGia.InputBox.CueText = "";
                    if (IsNumber(kryptonDataGridView2[2, selectedRowIndex].Value.ToString().Trim()))
                    {
                        String temp = kryptonDataGridView2[2, selectedRowIndex].Value.ToString();
                        decimal donGia = decimal.Parse(temp);
                        this.qcibDonGia.InputBox.Text = "$" + String.Format("{0:N0}", donGia);
                    }
                    else
                    {
                        MessageBox.Show("Value of cost has invalid");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    throw ex;
                }

            }
            else
            {
                this.qcibDonGia.InputBox.CueText = "";
                this.qcibDonGia.InputBox.Text = "";
            }

            if (kryptonDataGridView2[3, selectedRowIndex].Value != null)
            {
                this.qcibLoaiXe.InputBox.CueText = "";
                this.qcibLoaiXe.InputBox.Text = kryptonDataGridView2[3, selectedRowIndex].Value.ToString();
            }
            else
            {
                this.qcibLoaiXe.InputBox.CueText = "";
                this.qcibLoaiXe.InputBox.Text = "";
            }
        }

        private void kryptonDataGridView2_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //Enable button if there are items shown
            this.qcbTaoMoi.Enabled = (kryptonDataGridView2.RowCount > 0);
            this.qcbCapNhat.Enabled = (kryptonDataGridView2.RowCount > 0);
            this.qcbXoa.Enabled = (kryptonDataGridView2.RowCount > 0);

            //Binding data from datagridview to textboxes
            int selectedRowIndex = kryptonDataGridView2.SelectedCells[0].RowIndex;
            if (kryptonDataGridView2[0, selectedRowIndex].Value != null)
            {
                this.qcibMaHang.InputBox.CueText = "";
                this.qcibMaHang.InputBox.Text = kryptonDataGridView2[0, selectedRowIndex].Value.ToString();
            }
            else
            {
                this.qcibMaHang.InputBox.CueText = "";
                this.qcibMaHang.InputBox.Text = "";
            }

            if (kryptonDataGridView2[1, selectedRowIndex].Value != null)
            {
                this.qcibTenHang.InputBox.CueText = "";
                this.qcibTenHang.InputBox.Text = kryptonDataGridView2[1, selectedRowIndex].Value.ToString();
            }
            else
            {
                this.qcibTenHang.InputBox.CueText = "";
                this.qcibTenHang.InputBox.Text = "";
            }

            if (kryptonDataGridView2[2, selectedRowIndex].Value != null)
            {
                try
                {
                    this.qcibDonGia.InputBox.CueText = "";
                    if (IsNumber(kryptonDataGridView2[2, selectedRowIndex].Value.ToString().Trim()))
                    {
                        String temp = kryptonDataGridView2[2, selectedRowIndex].Value.ToString();
                        decimal donGia = decimal.Parse(temp);
                        this.qcibDonGia.InputBox.Text = "$" + String.Format("{0:N0}", donGia);
                    }
                    else
                    {
                        MessageBox.Show("Value of cost has invalid");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    throw ex;
                }

            }
            else
            {
                this.qcibDonGia.InputBox.CueText = "";
                this.qcibDonGia.InputBox.Text = "";
            }

            if (kryptonDataGridView2[3, selectedRowIndex].Value != null)
            {
                this.qcibLoaiXe.InputBox.CueText = "";
                this.qcibLoaiXe.InputBox.Text = kryptonDataGridView2[3, selectedRowIndex].Value.ToString();
            }
            else
            {
                this.qcibLoaiXe.InputBox.CueText = "";
                this.qcibLoaiXe.InputBox.Text = "";
            }
        }

        public bool IsNumber(string pText)
        {
            Regex regex = new Regex(@"^[-+]?[0-9]*\.?[0-9]+$");
            return regex.IsMatch(pText);
        }

        private void kryptonDataGridView2_DragEnter(object sender, DragEventArgs e)
        {
            MessageBox.Show("Enter");
        }

        private void FrmPart_Load(object sender, EventArgs e)
        {
            //Clear focus on datagridview when application starts
            kryptonDataGridView2.ClearSelection();
        }

        private void kryptonDataGridView2_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter || e.KeyChar == (char)Keys.Up || e.KeyChar == (char)Keys.Down)
            {
                DataGridViewRow selectedRow = kryptonDataGridView2.CurrentRow;
                int selectedRowIndex = selectedRow.Index;
                bindData(selectedRowIndex);
            }
        }

        private void kryptonDataGridView2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Down)
            {
                int selectedRowIndex = kryptonDataGridView2.CurrentRow.Index;
                if (selectedRowIndex >= 0 && selectedRowIndex < kryptonDataGridView2.RowCount -1)
                {
                    bindData(selectedRowIndex + 1);
                }
            }
            if (e.KeyCode == Keys.Up)
            {
                int selectedRowIndex = kryptonDataGridView2.CurrentRow.Index;
                if (selectedRowIndex >= 0 && selectedRowIndex < kryptonDataGridView2.RowCount)
                {
                    if (selectedRowIndex == 0)
                    {
                        bindData(0);
                        return;
                    }
                    bindData(selectedRowIndex - 1);
                }
            }
        }

        private void qcbThem_ItemActivated(object sender, Qios.DevSuite.Components.QCompositeEventArgs e)
        {
            //Validation...

            string kho = "";
            if(qcibKhoPhu.InputBox.Text != null || qicbKhoChinh.InputBox.Text != null)
            {
                if(qcibKhoPhu.InputBox.Text != null && qicbKhoChinh.InputBox.Text == null)
                {
                    kho = qcibKhoPhu.InputBox.Text;
                }
                else if(qicbKhoChinh.InputBox.Text != null && qcibKhoPhu.InputBox.Text == null)
                {
                    kho = qicbKhoChinh.InputBox.Text;
                }
            }
            using (var service = new BusinessServiceClient())
            {
                PhuTung pt = new PhuTung{ID = qcibMaHang.InputBox.Text,
                                            Ten = qcibTenHang.InputBox.Text,
                                            MaThayThe = qcibMaThayThe.InputBox.Text,
                                            MauSac = qcibMau.InputBox.Text,
                                            DonGia = int.Parse(qcibDonGia.InputBox.Text),
                                            GiaCongTy = int.Parse(qcibGiaCongTy.InputBox.Text),
                                            GiaBanLe = int.Parse(qcibGiaBanLe.InputBox.Text),
                                            PhanLoai = qcibPL.InputBox.Text,
                                            Model = qcibLoaiXe.InputBox.Text,
                                            SoChungTu = qcibSoChungTu.InputBox.Text,
                                            TienVenh = int.Parse(qcibTienVenh.InputBox.Text)};

                service.AddPart(pt);             
                pt.NhapHang.Add(new NhapHang{Kho = service.GetWareHouseByName(kho),SoLuongNhap =  int.Parse(qcibNhap.InputBox.Text),NgayNhap = Convert.ToDateTime(qcibNgayNhap.InputBox.Text),PhuTung = pt});
                pt.XuatHang.Add(new XuatHang{Kho = service.GetWareHouseByName(kho),SoLuongXuat = int.Parse(qcibXuat.InputBox.Text),NgayXuat= DateTime.Now, PhuTung = pt});
                service.UpdateRecord();

                //update to datagrid
                int index = kryptonDataGridView2.Rows.Add();
                kryptonDataGridView2.Rows[index].Cells[0].Value = pt.Ten;
                kryptonDataGridView2.Rows[index].Cells[1].Value = pt.ID;
                kryptonDataGridView2.Rows[index].Cells[2].Value = pt.DonGia;
                kryptonDataGridView2.Rows[index].Cells[3].Value = pt.Model;
                

            }
        }

        private void qcbXoa_ItemActivated(object sender, Qios.DevSuite.Components.QCompositeEventArgs e)
        {
            //validation
            if (MessageBox.Show("Các thông tin nhập, xuất có liên quan sẽ bị xóa theo. Bạn có chắc chắn muốn thực hiện", "Xóa", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                using (var service = new BusinessServiceClient())
                {
                    PhuTung pt = service.getPartByID(qcibMaHang.InputBox.Text);
                    service.DeleteAllImport(pt);
                    service.DeleteAllExport(pt);
                    service.DeletePart(pt);
                    service.UpdateRecord();

                    //Update to GUI
                    kryptonDataGridView2.Rows.RemoveAt(kryptonDataGridView2.SelectedRows[0].Index);
                }
            }
        }

        private void qcbCapNhat_ItemActivated(object sender, Qios.DevSuite.Components.QCompositeEventArgs e)
        {
            using (var service = new BusinessServiceClient())
            {
                PhuTung pt = service.getPartByID(qcibMaHang.InputBox.Text);
                
                    pt.Ten = qcibTenHang.InputBox.Text;
                    pt.MaThayThe = qcibMaThayThe.InputBox.Text;
                    pt.MauSac = qcibMau.InputBox.Text;
                    pt.DonGia = int.Parse(qcibDonGia.InputBox.Text);
                    pt.GiaCongTy = int.Parse(qcibGiaCongTy.InputBox.Text);
                    pt.GiaBanLe = int.Parse(qcibGiaBanLe.InputBox.Text);
                    pt.PhanLoai = qcibPL.InputBox.Text;
                    pt.Model = qcibLoaiXe.InputBox.Text;
                    pt.SoChungTu = qcibSoChungTu.InputBox.Text;
                    pt.TienVenh = int.Parse(qcibTienVenh.InputBox.Text);
                    service.UpdatePart(pt);
                //Update to GUI
                //reload datagridview here
                    reload();
            }
             
        }

        private void qcibMaHang_InputBox_Leave(object sender, EventArgs e)
        {
            errorProvider.SetError(qcibMaHang.InputBox, null);
            if (string.IsNullOrEmpty(qcibMaHang.InputBox.Text))
            {
                errorProvider.SetError(qcibMaHang.InputBox, "Bạn phải nhập Mã Phụ Tùng.");
            }
        }

        private void qcibDonGia_InputBox_Leave(object sender, EventArgs e)
        {
            errorProvider.SetError(qcibDonGia.InputBox, null);
            if (string.IsNullOrEmpty(qcibDonGia.InputBox.Text))
            {
                errorProvider.SetError(qcibDonGia.InputBox, "Bạn phải nhập đơn giá.");
            }
        }

        private void qcibGiaCongTy_InputBox_Leave(object sender, EventArgs e)
        {
            errorProvider.SetError(qcibGiaCongTy.InputBox, null);
            if (string.IsNullOrEmpty(qcibGiaCongTy.InputBox.Text))
            {
                errorProvider.SetError(qcibGiaCongTy.InputBox, "Bạn phải nhập giá công ty.");
            }
        }

        private void qcibGiaBanLe_InputBox_Leave(object sender, EventArgs e)
        {
            errorProvider.SetError(qcibGiaBanLe.InputBox, null);
            if (string.IsNullOrEmpty(qcibGiaBanLe.InputBox.Text))
            {
                errorProvider.SetError(qcibGiaBanLe.InputBox, "Bạn chưa nhập giá bán lẻ.");
            }
        }

        private void qcibTienVenh_InputBox_Leave(object sender, EventArgs e)
        {
            
        }

        private void qcibNhap_InputBox_Leave(object sender, EventArgs e)
        {
            errorProvider.SetError(qcibNhap.InputBox, null);
            if (string.IsNullOrEmpty(qcibNhap.InputBox.Text))
            {
                errorProvider.SetError(qcibNhap.InputBox, "Bạn chưa nhập số lượng phụ tùng được nhập.");
            }
        }

        private void qcibXuat_InputBox_Leave(object sender, EventArgs e)
        {
            errorProvider.SetError(qcibXuat.InputBox, null);
            if (string.IsNullOrEmpty(qcibXuat.InputBox.Text))
            {
                errorProvider.SetError(qcibXuat.InputBox, "Bạn chưa nhập số lượng phụ tùng được xuất kho.");
            }
        }
    }
    public class data : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private String m_strTenHang;

        public String StrTenHang
        {
            get { return m_strTenHang; }
            set { m_strTenHang = value; this.NotifyPropertyChanged("StrTenHang"); }
        }
        private String m_strMaHang;

        public String StrMaHang
        {
            get { return m_strMaHang; }
            set
            {
                m_strMaHang = value;
                this.NotifyPropertyChanged("StrMaHang");
            }
        }

        private String m_strDonGia;

        public String StrDonGia
        {
            get { return m_strDonGia; }
            set
            {
                m_strDonGia = value;
                this.NotifyPropertyChanged("StrDonGia");
            }
        }

        private String m_strLoaixe;

        public String StrLoaixe
        {
            get { return m_strLoaixe; }
            set
            {
                m_strLoaixe = value;
                this.NotifyPropertyChanged("StrLoaiXe");
            }
        }


        public data(String p_strTenHang, String p_strMaHang, String p_strDonGia, String p_strLoaiXe)
        {
            this.m_strMaHang = p_strMaHang;
            this.m_strTenHang = p_strTenHang;
            this.m_strDonGia = p_strDonGia;
            this.m_strLoaixe = p_strLoaiXe;
        }
        private void NotifyPropertyChanged(string name)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(name));
        }

    }
}
